/* eslint-disable no-console */
/* eslint-disable react/jsx-no-bind */
import { Card } from 'antd'
import { useCallback, useEffect, useState } from 'react'
import { render } from 'react-dom'
import '@slardar/hybrid'

interface Transport {
  [k: string]: (...args: any[]) => any
}

const SlardarHybrid = (window as any).SlardarHybrid as any

const config = JSON.parse(new URL(location.href).searchParams.get('config') || '{}')

function post(postUrl: string, args: { [key: string]: any }) {
  const xhr = new XMLHttpRequest()
  xhr.open('POST', postUrl)
  xhr.send(JSON.stringify(args))
}

const transport: Transport = {
  config: (...args) => console.log(args, 'config'),
  reportDirectly: (...args) => console.log(args, 'report'),
  cover: (...args) => post('test-perf', args),
  customReport: (...args) => console.log(args, 'custom'),
}

if (localStorage.batch) {
  transport.batch = (...args) => {
    console.log(JSON.parse(JSON.stringify(args)), 'batch')
  }
}

SlardarHybrid('config', {
  bid: 'slardar-cypress',
  enablePerformance: true,
  transport,
  ...config,
})

const $root = document.querySelector('#app')
const App = () => {
  const onClick = useCallback(() => {
    try {
      throw Error('custom error')
    } catch (error) {
      SlardarHybrid('captureException', error)
      SlardarHybrid('captureException', 'string error message', { context: { a: 1, b: 2 } })
      SlardarHybrid('captureException', {}, { context: 'abcdefg' })
      // illegal inputs
      SlardarHybrid('captureException')
      SlardarHybrid('captureException', 1234)
      SlardarHybrid('captureException', null)
      SlardarHybrid('captureException', new Date())
    }
  }, [])

  const onClick2 = useCallback(() => {
    console.log(SlardarHybrid('getLatestPerformance'))
  }, [])

  const onClick3 = useCallback(() => {
    console.log(SlardarHybrid('getLatestResource'))
  }, [])

  const onClick4 = useCallback(() => {
    console.log(SlardarHybrid('getCommonParams'))
  }, [])

  const onBatchClick = useCallback(() => {
    Array.from({ length: 5 }).forEach((_v, index) => {
      SlardarHybrid('emit', 'custom', {
        eventName: 'batch-custom',
        level: 8,
        metrics: {
          duration: 100,
          index,
          abc: 123,
        },
        category: {
          ev_from: 'bcd',
        },
        timing: {
          start: 123123123,
        },
        extra: {
          name: 'asd',
        },
      })
    })
  }, [])

  const onBatchSendClick = useCallback(() => {
    Array.from({ length: 5 }).forEach((_v, index) => {
      SlardarHybrid('emit', 'custom', {
        eventName: 'batch-custom',
        metrics: {
          duration: 100,
          index,
          abc: 456,
        },
        category: {
          ev_from: 'bcd',
        },
      })
    })

    SlardarHybrid('send')
  }, [])

  const onClickCustom = useCallback(() => {
    SlardarHybrid('emit', 'custom', {
      eventName: 'lalala',
    })

    SlardarHybrid('emit', 'custom', {
      eventName: 'abc',
      metrics: {
        duration: 100,
        abc: 123,
      },
      category: {
        ev_from: 'bcd',
      },
    })

    SlardarHybrid('emit', 'custom', {
      eventName: 'illegalParams1',
      metrics: {
        duration: '123',
      },
    })

    SlardarHybrid('emit', 'custom', {})
  }, [])

  const onClickFetch = useCallback(() => {
    fetch('http://localhost:8080/oncollect/fetch')
  }, [])

  const onClickAjax = useCallback(() => {
    const xhr = new XMLHttpRequest()
    xhr.open('GET', 'http://localhost:8080/oncollect/xhr')
    xhr.send()
  }, [])

  const onClickStatic = useCallback(() => {
    const imgEle = document.createElement('img')
    imgEle.src = 'http://localhost:8080/unexist.png'
    document.body.appendChild(imgEle)
  }, [])

  const onClickStaticSRI = useCallback(() => {
    const script = document.createElement('script')
    script.setAttribute('type', 'text/javascript')
    script.setAttribute('src', 'http://tosv.byted.org/obj/infinity/olbgp.js')
    script.setAttribute('integrity', 'sha384-we28jtBRy+u+xjjqWbsGRnktXhlq6H/4Ca+3AnmfVUj2t1mGlTEd+HiVzsersTxf')
    script.setAttribute('crossorigin', 'anonymous')
    document.body.appendChild(script)
  }, [])

  // 通过 async 函数产生一个异步错误
  const onClickJsErr = useCallback(() => {
    const a = [1, 2, 3]
    for (let i = 0; i < 5; i++) {
      a[i].toString()
    }
  }, [])

  const [enableImage, setEnableImage] = useState(false)
  const onStaticErr = useCallback(() => {
    setEnableImage(true)
    const imgEle = document.createElement('img')
    imgEle.src = '/unexist.png?a=1&b=2#hash'
    document.body.appendChild(imgEle)
  }, [])

  const onPerformanceSend = useCallback(() => {
    SlardarHybrid('performanceSend')
  }, [])

  const onPerformanceInit = useCallback(() => {
    SlardarHybrid('performanceInit')
  }, [])

  const onConfigBid = useCallback(() => {
    SlardarHybrid('config', {
      bid: 'test-bid',
    })
  }, [])

  useEffect(() => {
    Promise.reject('unhandle rejection')
  }, [])

  return (
    <div className="app">
      <div id="click" onClick={onClick}>
        Click
      </div>
      <div id="click2" onClick={onClick2}>
        Click2
      </div>
      <div id="click3" onClick={onClick3}>
        Click3
      </div>
      <div id="click4" onClick={onClick4}>
        Click4
      </div>
      <div id="batch_click" onClick={onBatchClick}>
        Batch Report Click
      </div>
      <div id="batch_send_click" onClick={onBatchSendClick}>
        Batch Report Click and send directly
      </div>
      <div id="custom_click" onClick={onClickCustom}>
        Custom Report Click
      </div>
      <div id="fetch_click" onClick={onClickFetch}>
        Fetch_Click
      </div>
      <div id="ajax_click" onClick={onClickAjax}>
        Ajax_Click
      </div>
      <div id="static_click" onClick={onClickStatic}>
        Static_Click
      </div>
      <div id="static_sri_error" onClick={onClickStaticSRI}>
        Static_SRI_Click
      </div>
      {[...new Array(22).keys()].map((i) => (
        <div key={i} id={`breadcrumb_item_${i}`}>{`breadcrumb ${i}`}</div>
      ))}
      <div id="jserr_with_breadcrumb" onClick={onClickJsErr}>
        JS_Error_With_Breadcrumb
      </div>
      <div id="static_err" onClick={onStaticErr}>
        Static_Error
      </div>
      <div id="performance_send" onClick={onPerformanceSend}>
        Performance Send
      </div>
      <div id="performance_init" onClick={onPerformanceInit}>
        Performance Init
      </div>
      <div id="config_bid" onClick={onConfigBid}>
        config bid test-bid
      </div>
      <Card>
        <h1>Slardar SDK 222</h1>
        <p>Testing by cypress</p>
        {enableImage ? <img src="https://s3a.pstatp.com/rangers/test.png" style={{ width: 100, height: 100 }} /> : null}
      </Card>
    </div>
  )
}

render(<App />, $root!)

setTimeout(() => {
  const d = document.createElement('div')
  d.style.background = 'red'
  d.style.width = '100px'
  d.style.height = '100px'
  document.body.append(d)
}, 2)
